package com.mediacloud.app.newsmodule.fragment.works

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.quanzi.model.BaseDataBean
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.appcloud.project.gxapp.view.widget.CommonDialog
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.fragment_mydraftbox.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


/**
 *草稿箱
 */
class MyDraftBoxFragment : BaseFragment(), OnRefreshLoadMoreListener {
    var pageNumber = 1
    var pageSize = 20
    val adapter by lazy {
        DraftBoxAdapter()
    }

    override fun getLayoutResID(): Int {
        return R.layout.fragment_mydraftbox
    }

    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        emptyText?.setOnClickListener {
            freshData()
        }
        showStateView(TYPE_LOADING, false)
        freshLayout.setOnRefreshLoadMoreListener(this)
        rvLayout.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        rvLayout.adapter = adapter
        adapter.setOnItemClickListener { adapter, view, position ->

            val item = adapter.getItem(position) as ArticleBean
            val intent = Intent()
            if ("1" == item.type) {
                intent.setClassName(
                    requireContext(),
                    "com.mediacloud.app.appfactory.activity.contribute.ImagePickActivity"
                )
            } else {
                intent.setClassName(
                    requireContext(),
                    "com.mediacloud.app.appfactory.activity.contribute.VideoPickActivity"
                )
            }
            intent.putExtra("articleId", item.articleId)
            startActivity(intent)

        }


        clearAll.setOnClickListener {
            CommonDialog.Builder().builder(context)
                .setTitle("")
                .setMsg("确认清空草稿箱吗?")
                .setLeftButton(getString(R.string.quxiao))
                .setRightBotton("确认") { _, _ -> //清空
                    deleteAll()
                }
                .create()
                .show()

        }
        clearIds.setOnClickListener {
            CommonDialog.Builder().builder(context)
                .setTitle("")
                .setMsg("确认删除选中草稿吗?")
                .setLeftButton(getString(R.string.quxiao))
                .setRightBotton("确认") { _, _ -> //清空
                    deleteIds()
                }
                .create()
                .show()

        }

        getData()
    }

    private fun deleteIds() {
        val jsonObject = JSONObject()
        val userInfo = UserInfo.getUserInfo(requireContext())
        var ids = StringBuilder()
        adapter.selectList.forEach {
            ids.append(it).append(',')
        }
        jsonObject.put("articleIds", ids.toString().trimEnd(','))
        jsonObject.put("userNick", userInfo.nickname)

        val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .deleteByArticleIds(body)
            .enqueue(object : Callback<BaseDataBean<String>> {
                override fun onResponse(call: Call<BaseDataBean<String>>, response: Response<BaseDataBean<String>>) {
                    if (response.body() != null && response.body()!!.isSuccess) {
                        freshData()
                    } else
                        ToastUtil.showToastCenter(requireContext(), "删除失败")

                }

                override fun onFailure(call: Call<BaseDataBean<String>>, t: Throwable) {
                    ToastUtil.showToastCenter(requireContext(), "删除失败")
                }

            })
    }

    private fun deleteAll() {
        val jsonObject = JSONObject()
        val userInfo = UserInfo.getUserInfo(requireContext())
        jsonObject.put("addUser", userInfo.userid)
        jsonObject.put("userNick", userInfo.nickname)

        val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .clearDraft(body)
            .enqueue(object : Callback<BaseDataBean<String>> {
                override fun onResponse(call: Call<BaseDataBean<String>>, response: Response<BaseDataBean<String>>) {
                    if (response.body() != null && response.body()!!.isSuccess) {
                        freshData()
                    } else {
                        ToastUtil.showToastCenter(requireContext(), "删除失败")
                    }
                }

                override fun onFailure(call: Call<BaseDataBean<String>>, t: Throwable) {
                    ToastUtil.showToastCenter(requireContext(), "删除失败")
                }

            })
    }

    private fun getData() {
        val jsonObject = JSONObject()
        jsonObject.put("pageNumber", pageNumber)
        jsonObject.put("pageSize", pageSize)
        jsonObject.put("addUser", UserInfo.getUserInfo(requireContext()).userid)
        jsonObject.put("status", 0)

        val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .getArticleList(body)
            .enqueue(object : Callback<BaseDataListBean<ArticleBean>> {
                override fun onResponse(
                    call: Call<BaseDataListBean<ArticleBean>>,
                    response: Response<BaseDataListBean<ArticleBean>>
                ) {
                    closeStateView()
                    freshLayout.finishRefresh()
                    if (response.isSuccessful) {
                        response.body()?.data?.let {
                            if (it.isHasNextPage) {
                                freshLayout.finishLoadMore()
                            } else {
                                freshLayout.finishLoadMoreWithNoMoreData()
                            }

                            it.pageRecords?.let { data ->
                                if (data.isEmpty()) {
                                    if (pageNumber == 1) {
                                        showStateView(TYPE_NO_CONTENT, false)
                                    }
                                } else {
                                    if (pageNumber == 1) {
                                        adapter.setNewData(data)
                                    } else {
                                        adapter.addData(data)
                                    }
                                }
                            }


                        }
                    }

                }

                override fun onFailure(call: Call<BaseDataListBean<ArticleBean>>, t: Throwable) {
                    showStateView(TYPE_NO_CONTENT, false)
                }

            })
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        freshData()

    }

    private fun freshData() {
        pageNumber = 1
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        pageNumber++
        getData()
    }

    fun showClearLayout(show: Boolean) {
        clearLayout.visibility = if (show) View.VISIBLE else View.GONE
        adapter.isEdit = show
        adapter.notifyDataSetChanged()
    }
}